package id.co.rho.scoring.cid.client.widgets;

import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.widget.Component;
import com.extjs.gxt.ui.client.widget.form.Field;

public class UIHelper {
	public static void renderedSafeFunctionCall(final Component c, final Function f) {
	    c.enableEvents(true);
	    if (c.isRendered()) {
	        f.execute();
	    } else {
	        final Listener lsnr = new Listener() {
	            @Override
	            public void handleEvent(final BaseEvent be) {
	                f.execute();
                    c.removeListener(Events.Render,this);
	            }
	        };
	        c.addListener(Events.Render, lsnr);
	    }
	}

	public static void visibleSafeFunctionCall(final Component c, final Function f) {
	    c.enableEvents(true);
	    if (c.isVisible()) {
	        f.execute();
	    } else {
	        final Listener lsnr = new Listener() {
	            @Override
	            public void handleEvent(final BaseEvent be) {
	                f.execute();
                    c.removeListener(Events.Show,this);
	            }
	        };
	        c.addListener(Events.Show, lsnr);
	    }
	}
	
	public static void applyDirtyMarker(final Field field) {
		renderedSafeFunctionCall(field, new Function() {

            @Override
            public void execute() {
//				field.el().firstChild().setStyleAttribute("background-color", "yellow");
//				field.el().firstChild().setStyleAttribute("background-image", "url(gxt/images/default/form/text-edited-bg.gif)");
                field.el().firstChild().addStyleName("text-field-dirty");
            }

        });
		
	}
	
	public static void removeDirtyMarker(final Field field) {
		renderedSafeFunctionCall(field, new Function() {

            @Override
            public void execute() {
//				field.el().firstChild().setStyleAttribute("background-color", null);
//				field.el().firstChild().setStyleAttribute("background-image", null);
                field.el().firstChild().removeStyleName("text-field-dirty");
            }
        });
	}
}
